﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;

namespace COFE.Core.Plugin
{    
    public abstract class PluginUserBase : IPluginUser, IComparable<IPluginUser> 
    {
        public PluginUserBase(int priority)
        {
            Priority = priority;
        }

        public int Priority { get; set; }

        public abstract void Apply(IPluginManager manager);

        protected IEnumerable<P> GetPlugins<P>(IPluginManager manager) where P : IPlugin
        {
            return manager.GetPlugins<P>();
        }

        protected T GetProperty<P, T>(IPluginManager manager, Func<P, T> propertyGetFunc)            
            where P : IPlugin
        {
            T retVal = default(T);
            foreach (var p in GetPlugins<P>(manager))
            {
                if (propertyGetFunc(p) != null)
                    retVal = propertyGetFunc(p);
            }
            return retVal;
        }

        protected IEnumerable<T> GetAllProperty<P, T>(IPluginManager manager, 
            Func<P, IEnumerable<T>> propertyGetFunc)
            where P : IPlugin
        {
            List<T> retVal = new List<T>();
            foreach (var p in GetPlugins<P>(manager))
            {
                retVal.AddRange(propertyGetFunc(p));                
            }
            return retVal;
        }

        public int CompareTo(IPluginUser other)
        {
            return Priority.CompareTo(other.Priority);
        }

    }
}
